<?php

namespace App\Models\Train\TrainOrderTrain\Repositories;

use App\Models\Train\TrainOrders\TrainOrder;
use App\Models\Train\TrainOrderTrain\Repositories\Interfaces\TrainOrderTrainRepositoryInterface;
use App\Models\Train\TrainOrderTrain\TrainOrderTrain;
use App\Trip\Repository\BaseRepository;
use Carbon\Carbon;

class TrainOrderTrainRepository extends BaseRepository implements TrainOrderTrainRepositoryInterface
{
    public function __construct(TrainOrderTrain $model)
    {
        parent::__construct($model);
    }

    /**
     * after  2022-08-03 一个订单只有一个 车次
     * 抢票时备选车次太多尽在订单里存相关json数据
     * ,此处构造会有大量的数据,所以废弃此处 多个车次数据
     *
     * @param TrainOrder $train_order
     * @param array      $data
     *
     * @return TrainOrderTrain
     */
    public function addTrain(TrainOrder $train_order, array $data): TrainOrderTrain
    {
        $data['user_id']     = $train_order->getUserId();
        $data['order_sn']    = $train_order->getOrderSn();
        $data['alternative'] = 0;
        $data['current']     = 1;// 当备选行程出票后 current =2
        $data['start_at']    = $data['start_date']." ".$data['start_time'];
        $data['arrive_at']   = $data['arrive_date']." ".$data['arrive_time'];
        if ($train_order_train = $this->findTrainByOrderAndTrainData($train_order, [])) {
            $this->update($data, $train_order_train);
            return $train_order_train->refresh();
        }
        return $this->create($data);
    }

    public function findTrainByOrderAndTrainData(TrainOrder $order, array $data): ?TrainOrderTrain
    {
        $data['order_sn'] = $order->getOrderSn();
        $data['user_id']  = $order->getUserId();
        return $this->findOneBy($data);
    }

    public function addAlternativeTrain(TrainOrder $train_order, array $data): TrainOrderTrain
    {
        $data['user_id']     = $train_order->getUserId();
        $data['order_sn']    = $train_order->getOrderSn();
        $data['alternative'] = 1;
        $data['current']     = 2; // 当备选行程出票后 current =1
        $data['start_at']    = $data['start_date']." ".$data['start_time'];
        $data['arrive_at']   = $data['arrive_date']." ".$data['arrive_time'];
        return $this->create($data);
    }

    public function findTrainByOrder(TrainOrder $order): TrainOrderTrain
    {
        $query = [
            'train_code'        => $order->getTrainCode(),
            'from_station_code' => $order->getFromStationCode(),
            'to_station_code'   => $order->getToStationCode(),
            'start_at'          => Carbon::parse($order->getTrainDate())->toDateTimeString(),
        ];
        return $this->findTrainByOrderAndTrainData($order, $query);
    }
}